jQuery(function() {
    jQuery("#reload-btn").click(function() {
        jQuery(this).addClass("disabled");
        setInterval(function() {
            window.location.reload();
        }, 200);
    });

    jQuery("#preview-btn").click(function() {
        var archiveId = PageContext.getLong("archiveId");
        var url = PageContext.getContextPath() + "/note/archive/display.html?archiveId=" + archiveId;
        window.open(url, "_blank");
    });

    jQuery("#save-btn").click(function() {
        var src = jQuery(this);

        if(src.hasClass("disabled")) {
            return;
        }

        src.addClass("disabled");

        var editor = JEditor.getInstance(jQuery("textarea[name=content]").get(0));
        window.location.href = "#top=" + Math.floor(editor.getDocument().body.scrollTop);

        var archiveId = PageContext.getLong("archiveId");
        var title = jQuery("#title").val();
        var content = editor.getSource();
        var pageNum = PageContext.getInt("pageNum");
        var version = PageContext.getLong("version");

        var params = {
            "archiveId": archiveId,
            "title": title,
            "mimeType": "text/html",
            "content": content,
            "pageNum": pageNum,
            "version": version
        };

        jQuery.ajax({
            "type": "post",
            "url": PageContext.getContextPath() + "/note/archive/save.html",
            "data": jQuery.param(params, true),
            "dataType": "json",
            "error": function() {
                src.removeClass("disabled");
                alert("系统错误，请稍后再试！");
            },
            "success": function(result) {
                src.removeClass("disabled");
                Response.success(result, function() {
                    setInterval(function() {
                        window.location.reload();
                    }, 200);
                });
            }
        });
    });
});

/**
 * 初始化编辑器
 */
jQuery(function() {
    var theme = PageContext.getAttribute("theme");
    var contextPath = PageContext.getContextPath();
    var textarea = jQuery("textarea[name=content]");
    textarea.attr("theme", contextPath + "/resource/note/theme/" + theme);
    textarea.attr("toolbar", "cut,copy,paste,|,formatBlock,fontName,fontSize,|,bold,italic,underline,strikethrough,foreColor,backColor,removeformat,|,align,list,dedent,indent,|,link,unlink,anchor,image,flash,media,hr,emot,table,|,source,fullscreen");
    textarea.jeditor();
});

/**
 * 上传支持
 */
jQuery(function() {
    var jeditor = null;
    var textarea = jQuery("textarea[name=content]");
    var editorId = textarea.attr("editorId");

    if(editorId == null) {
        return;
    }

    /**
     * @param path
     * @return String
     */
    var getName = function(path) {
        var k = path.lastIndexOf('?');

        if(k < 0) {
            k = path.length;
        }

        var i = path.lastIndexOf("/", k - 1);

        if(i > -1) {
            return path.substring(i + 1, k).toLowerCase();
        }
        return "";
    };

    /**
     * @param path
     * @return String
     */
    var getExtension = function(path) {
        var k = path.lastIndexOf('?');

        if(k < 0) {
            k = path.length;
        }

        var i = path.lastIndexOf(".", k - 1);

        if(i > -1) {
            return path.substring(i + 1, k).toLowerCase();
        }
        return "";
    };

    jeditor = JEditor.getInstance(editorId);

    /**
     * 上传插件
     */
    jeditor.uploader = new com.skin.upload.FileUpload({
        "accept": "",
        "multiple": false,
        "dataType": "json",
        "error": function() {
            alert("上传失败，请稍后再试！");
        },
        "select": function(files) {
            var archiveId = PageContext.getLong("archiveId");
            var url = PageContext.getContextPath() + "/note/upload.html?archiveId=" + archiveId;

            for(var i = 0; i < files.length; i++) {
                this.upload(url, "uploadFile", files[i], null);
            }
        },
        "success": function(result) {
            if(result == null || result.status != 200) {
                alert("上传失败，请稍后再试！");
                return;
            }

            var file = result.value;
            var panel = JEditor.ToolMenu.getContainer();

            if(panel.style.display == "block") {
                jQuery(panel).find("input[name=address]").val(file.filePath);
            }
            else {
                var ext = getExtension(file.filePath);

                if(ext == "bmp"
                    || ext == "jpg"
                    || ext == "jpeg"
                    || ext == "gif"
                    || ext == "png"
                    || ext == "ico") {
                    jeditor.pasteHtml("<img class=\"je-img\" src=\"" + file.filePath + "\"/><br/>");
                }
                else {
                    var html = [
                        "<div class=\"je-attach\" path=\"" + file.filePath + "\">",
                        "附件:&nbsp;<a href=\"" + PageContext.getContextPath() + "/note/attachment.html?path=",
                        encodeURIComponent(file.filePath),
                        "\" target=\"_blank\">",
                        file.fileName,
                        "</a></div><br/>"
                    ];
                    jeditor.pasteHtml(html.join(""));
                }
            }
        }
    });
});

/**
 * 自动定位到上次打开的位置
 */
jQuery(function() {
    var editor = JEditor.getInstance(jQuery("textarea[name=content]").get(0));

    var autoScroll = function() {
        var scrollTop = 0;
        var hash = window.location.hash;

        if(hash != null && hash.length > "#top=".length) {
            scrollTop = parseInt(hash.substring(5));

            if(isNaN(scrollTop)) {
                scrollTop = 0;
            }
        }

        if(scrollTop <= 0) {
            var archiveId = PageContext.getLong("archiveId");
            var bookmark = Footprint.getBookmark(archiveId);

            if(bookmark != null) {
                scrollTop = parseInt(bookmark.top);

                if(isNaN(scrollTop)) {
                    scrollTop = 0;
                }
            }
        }

        if(scrollTop > 0) {
            editor.getDocument().body.scrollTop = scrollTop;
            return;
        }
    };

    // editor.on("create", autoScroll);
    setTimeout(autoScroll, 500);
});

jQuery(function() {
    var lastScrollTop = 0;

    setInterval(function() {
        var archiveId = PageContext.getLong("archiveId");
        var editor = JEditor.getInstance(jQuery("textarea[name=content]").get(0));
        var scrollTop = Math.floor(editor.getDocument().body.scrollTop);

        if(scrollTop != lastScrollTop) {
            Footprint.setValue(archiveId, scrollTop);
        }
        window.location.href = "#top=" + scrollTop;
    }, 5000);
});

/*
jQuery(function() {
    var editor = JEditor.getInstance(jQuery("textarea[name=content]").get(0));

    editor.getPlugin("save").click = function() {
        editor.setEnabled("save", false);

        var archiveId = PageContext.getLong("archiveId");
        var title = jQuery("#title").val();
        var content = JEditor.getSource(jQuery("textarea[name=content]").get(0));
        var pageNum = PageContext.getInt("pageNum");

        var params = {
            "archiveId": archiveId,
            "title": title,
            "mimeType": "text/html",
            "content": content,
            "pageNum": pageNum
        };

        jQuery.ajax({
            "type": "post",
            "url": PageContext.getContextPath() + "/note/archive/save.html",
            "data": jQuery.param(params, true),
            "dataType": "json",
            "error": function() {
                editor.setEnabled("save", true);
                alert("系统错误，请稍后再试！");
            },
            "success": function(result) {
                editor.setEnabled("save", true);
                Response.success(result, function() {
                    window.location.reload();
                });
            }
        });
    };
});
*/

/**
 * debug使用
 */
var API = {};

API.getEditor = function() {
    /**
     * JEditor可使用的接口:
     * editor.getIFrame();
     * editor.getWindow();
     * editor.getDocument();
     */
    return JEditor.getInstance(jQuery("textarea[name=content]").get(0));
};
